#include "worker.h"

Worker::Worker(QObject *parent)
    : QObject{parent}
{
    // 打开python环境
    Py_Initialize();
}

void Worker::init(){
    // 将python包导入导包路径
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./TranslationPy')");
    // 获取python文件
    PyObject * pFile = PyImport_ImportModule("Translation");
    if (pFile == NULL){
        return;
    }
    // 获取文件属性字典
    PyObject* pDict = PyModule_GetDict(pFile);
    if (pDict == NULL){
        return;
    }
    // 从属性字典获取类
    PyObject* pClass = PyDict_GetItemString(pDict, "Translation");
    if (pClass == NULL){
        return;
    }
    // 从类中获取构造函数
    PyObject* pInit = PyInstanceMethod_New(pClass);
    if (pInit == NULL){
        return;
    }
    // 封装参数
    PyObject* args = PyTuple_New(2);
    PyTuple_SetItem(args, 0, Py_BuildValue("s", "你的应用id"));
    PyTuple_SetItem(args, 1, Py_BuildValue("s", "你的应用密钥"));
    // 实例化构造函数
    PyObject* pObj = PyObject_CallObject(pInit, args);
    if (pObj == NULL){
        return;
    }
    this->pObj = pObj;
    PyObject_CallMethod(pObj, "set_language", "s", "Language.json");
    // 获取列表
    PyObject* pList = PyObject_CallMethod(pObj, "get_language", "");
    this->save_list(&pList);
    // 发送完成信号
    emit this->ready_list();
}

void Worker::save_list(PyObject **pList){
    // 获取列表长度
    int size = PyObject_Size(*pList);
    this->languageList = QStringList();
    // 循环取出列表的元素并保存
    for (int var = 0; var < size; var++) {
        PyObject* item = PyList_GetItem(*pList, var);
        char *title;
        PyArg_Parse(item, "s", &title);
        this->languageList << title;
    }
}

void Worker::request(char *q, char *m_from, char *m_to){
    PyObject_CallMethod(this->pObj, "request", "sss", q, m_from, m_to);
    PyObject* res = PyObject_CallMethod(this->pObj, "get_response", "");
    char *response;
    PyArg_Parse(res, "s", &response);
    emit this->send_response(response);
}

Worker::~Worker(){
    // 关闭Python环境
    Py_Finalize();
}
